package com.example.composableexample

import androidx.compose.animation.AnimatedVisibility
import androidx.compose.animation.AnimatedVisibilityScope
import androidx.compose.animation.ExperimentalAnimationApi
import androidx.compose.animation.core.tween
import androidx.compose.animation.scaleIn
import androidx.compose.animation.scaleOut
import androidx.compose.foundation.Image
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.window.Dialog
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch

/**
 * author: LiLiang
 * createTime: 2022/9/14-9:49
 * remark:
 **/

internal const val ANIMATION_TIME = 1000L
internal const val DIALOG_SCALE_TIME = 300L

@Composable
fun AnimatedTransitionDialog(
    onDismissRequest: () -> Unit,
    contentAlignment: Alignment = Alignment.Center,
    content: @Composable () -> Unit
) {
    val animateTrigger = remember {
        mutableStateOf(false)
    }
    LaunchedEffect(key1 = Unit) {
        launch {
            delay(DIALOG_SCALE_TIME)
            animateTrigger.value = true
        }
    }
    Dialog(onDismissRequest = onDismissRequest) {
        Box(
            modifier = Modifier.fillMaxSize(),
            contentAlignment = contentAlignment
        ) {
            AnimateScaleInTransition(visible = animateTrigger.value) {
                content()
            }
        }
    }
}

@OptIn(ExperimentalAnimationApi::class)
@Composable
internal fun AnimateScaleInTransition(
    visible: Boolean,
    content: @Composable AnimatedVisibilityScope.() -> Unit
) {
    AnimatedVisibility(
        visible = visible,
        enter = scaleIn(
            animationSpec = tween(ANIMATION_TIME.toInt())
        ),
        exit = scaleOut(
            animationSpec = tween(ANIMATION_TIME.toInt())
        ),
        content = content
    )
}


@Preview
@Composable
fun DialogExample() {
    AnimatedTransitionDialog(onDismissRequest = { /*TODO*/ }) {
        Image(
            painter = painterResource(id = R.drawable.jetpack), contentDescription = ""
        )
    }
}